<template>
  <div id="animation_slit">
    <div class="search-box">
      <Row type='flex' justify="space-between" align='middle'>
        <Row type='flex' align='middle'>
          <Col class="search-item">
            <span class="sign"></span>
          </Col>
          <Col class="search-item sign1"><span>{{this.$route.query.shopName}}</span></Col>
        </Row>
        <Col class="search-item">
          <Button style="margin-right:24px" @click="allSet">批量设置</Button>
        </Col>
      </Row>
      <Row type='flex' align='middle'>
        <Col class="search-item"><span>机台名称：</span><Input placeholder="请输入" v-model='machineName' style="width:180px" :maxlength='20' /></Col>
        <Col class="search-item">
          <span>机台分类：</span>
          <Select v-model="machineType" @on-change="selectType">
            <Option v-for="item in machineTypeList" :value="item.machineCategoryId" :key="item.machineCategoryId">{{ item.name }}</Option>
          </Select>
        </Col>
        <Col class="search-item">
          <span>执行状态：</span>
          <Select v-model="operationStatus" @on-change="doSearch">
            <Option v-for="item in operationStatusList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col class="search-item">
          <Button type="primary" class="draw-btn" @click="doSearch">查询</Button>
        </Col>
        <Col class="search-item">
          <Button class="draw-btn" @click="reset">重置</Button>
        </Col>
      </Row>
    </div>
    <Table :columns="columns" :data="tableData" class="table-list table-show" :height='getTableHeight' :loading='loading'>
      <template slot-scope="{ row }" slot="animation">
        <div class="animation-img">
          <img :src="row.configValue" alt="">
        </div>
      </template>
      <template slot-scope="{ row }" slot="exeStatus">
        <span>{{ row.exeStatus === 0? '未更新' : row.exeStatus === 1?'已更新':''}}</span>
      </template>
      <template slot-scope="{ row }"
                  slot="action">
          <i class="iconsys iconsetting" @click="setSlit('1', row)"
            title="设置"></i>
          <i class="iconsys iconzhongqi" @click="reStart(row)"
            title="重启"></i>
            <i class="iconsys iconlishijilu" @click="setSlit('2', row)"
              title="历史记录"></i>
        </template>
    </Table>
    <Row type='flex' justify="end" style="padding:20px">
      <Col>
        <Page :total="pageObj.total"
            :current="pageObj.pageIndex"
            :page-size="pageObj.pageSize"
            show-sizer
            show-total
            @on-change='changePageIndex'
            @on-page-size-change='changePageSize' />
      </Col>
    </Row>
    <select-shop :checkdList="checkdList" :titleObj='titleObj'
      :dataTree="dataTree"
      :modalShow="modalShow"
      @oncancel="selctshopCancel"
      @selctshop="volumeSet"
      v-if="modalShow">
    </select-shop>
    <!-- 二次弹框 -->
    <Modal class="twice-modal-set" width='684'
        v-model="setModalStatus"
        :scrollable='true'
        :transfer='false'
         :closable='true'
         :mask-closable='false'
         @on-cancel="cancelModal"
        title="设置配置项">
        <dl class="animation-set">
          <dd v-for="(item,idx) in animationList" :key='idx'>
            <div class="check-icon" @click="checkMaterial(item)">
              <!-- <Icon :type="checkedUrl === item.url?'ios-checkmark-circle':'ios-alert-outline'" size='24' /> -->
              <Icon type="ios-checkmark-circle" style="color:#2D8CF0" size='24' v-if='checkedUrl === item.url' />
              <span style="background: #fff;display:inline-block;width:20px;height:20px;border-radius:50%" v-if='checkedUrl !== item.url'></span>
            </div>
            <div>
              <img :src="item.url" alt="">
            </div>
            <p class="desc">{{item.createTime}}</p>
          </dd>
        </dl>
        <div slot="footer">
          <Row style="margin-bottom:12px">
            <Col>
              <Page :total="animationObj.total"
              :current="animationObj.pageIndex"
              :page-size="animationObj.pageSize"
              :page-size-opts='[12, 24, 36, 48]'
              show-sizer
              show-total
              @on-change='changePageIndexAnimation'
              @on-page-size-change='changePageSizeAnimation' />
            </Col>
          </Row>
          <Button style="margin-right:10px;width:80px" @click="skipPrevious">上一步</Button>
          <Button type="primary" style='width:80px' @click="sureSet">确定</Button>
        </div>
    </Modal>
    <drawer-set
    :checkedUrl ='checkedUrl'
    :isDisabled ='isDisabled'
      :historyStatus='historyStatus'
      :title="title"
      :showType='showType'
      :columnsHistory='columnsHistory'
      :animationList='animationList'
      :historyData='tableHistoryData'
      :pageObj="historyObj"
      @submit='submit'
      @selectMaterial='selectMaterial'
      @oncolse="drawerSetClose"
      @onChangePageIndex='onChangePageIndex'
      @onChangePageSize='onChangePageSize'></drawer-set>
  </div>
</template>

<script>
import { slitAnimationList, iterationHistoryList, setSlitPort, lookAnimationList } from '@/api/setting'
import SelectShop from '@/view/components/select-machine/select-machine.vue'
import DrawerSet from '@/view/components/drawer-set/drawer-set.vue'
import machine from '@/view/setting/components/own-use/machine'
export default {
  name: 'animation_slit',
  mixins: [machine],
  components: {
    DrawerSet, SelectShop
  },
  computed: {
    getTableHeight () {
      let height = this.tableData.length > 5 ? 520 : 0
      return height
    }
  },
  watch: {
    historyStatus (val) {
      if (!val) {
        this.animationList = []
        this.checkedUrl = ''
        this.selectedImg = ''
        this.historyObj = {
          pageIndex: 1,
          pageSize: 10
        }
      }
    },
    setModalStatus (status) {
      if (!status) {
        this.checkedUrl = ''
        this.animationObj.total = 0
        this.animationObj.pageIndex = 1
        this.animationObj.pageSize = 12
        if (!this.modalShow) {
          this.checkdList = []
          this.dataTree = []
          this.checkedUrl = ''
        }
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.queryShopId !== to.query.shopId || vm.queryType !== to.query.type) {
        vm.queryShopId = to.query.shopId
        vm.queryType = to.query.type
        vm.operationStatus = to.query.type === '0' ? '0' : ''
        vm.machineName = ''
        vm.machineType = ''
        vm.pageObj.pageIndex = 1
        vm.pageObj.pageSize = 10
        vm.getData()
      }
    })
  },
  data () {
    return {
      queryShopId: '',
      queryType: '',
      showType: '1', // 1表示历史记录  2表示设置drawer
      loading: true,
      selectedImg: '',
      checkedUrl: '',
      isDisabled: false,
      title: '历史记录',
      historyStatus: false,
      searchValue: '',
      machineName: '', // 机台名称
      machineType: '', // 机台分类
      operationStatus: '',
      setAnimationList: [],
      animationList: [],
      tableData: [],
      tableHistoryData: [],
      animationObj: {
        total: 0,
        pageIndex: 1,
        pageSize: 12
      },
      operationStatusList: [
        { value: '0', label: '未更新' },
        { value: '1', label: '已更新' }
      ],
      columns: [
        {
          title: '机台名称',
          key: 'machineInstanceName'
        },
        {
          title: ' 投币口名称',
          key: 'machineInstanceSoltCode'
        },
        {
          title: '机台分类',
          key: 'categoryName'
        },
        {
          title: '待机动画物料',
          slot: 'animation'
        },
        {
          title: '返回状态',
          slot: 'exeStatus'
        },
        {
          title: '操作时间',
          key: 'operTime'
        },
        {
          title: '操作',
          slot: 'action'
        }
      ],
      columnsHistory: [
        {
          title: '发布时间',
          key: 'createTime'
        },
        {
          title: '操作人',
          key: 'creatorName',
          width: 160
        },
        {
          title: '待机动画物料',
          slot: 'meratail'
        }
      ]
    }
  },
  methods: {
    volumeSet (val) {
      this.modalShow = false
      this.setModalStatus = true
      this.checkdList = val
      this.gainAnimationList()
      // 此处请求选择好门店后，设置固件
    },
    checkMaterial (item) {
      this.animationList.forEach((ele, idx) => {
        if (ele.url === item.url) {
          this.checkedUrl = item.url
        }
      })
    },
    doSearch () {
      this.pageObj.pageIndex = 1
      this.getData()
    },
    // 选择机台分类
    selectType () {
      this.getData()
    },
    // 选择执行状态
    selectOperation () {},
    changePageIndexAnimation (index) {
      this.animationObj.pageIndex = index
      this.gainAnimationList()
    },
    changePageSizeAnimation (size) {
      this.animationObj.pageSize = size
      this.animationObj.pageIndex = 1
      this.gainAnimationList()
    },
    // 操作分页
    changePageIndex (index) {
      this.pageObj.pageIndex = index
      this.getData()
    },
    changePageSize (size) {
      this.pageObj.pageSize = size
      this.pageObj.pageIndex = 1
      this.getData()
    },
    // 操作draw分页
    onChangePageIndex (index) {
      this.historyObj.pageIndex = index
      if (this.title === '历史记录') {
        this.getHistoryList()
      } else {
        this.getAnmanationList()
      }
    },
    onChangePageSize (size) {
      this.historyObj.pageSize = size
      this.historyObj.pageIndex = 1
      if (this.title === '历史记录') {
        this.getHistoryList()
      } else {
        this.getAnmanationList()
      }
    },
    sureSet () {
      if (this.checkedUrl) {
        let arr = this.checkdList.map(item => {
          return item.machineInstanceId
        })
        setSlitPort({
          merchantId: this.$store.state.user.merchantId,
          type: 2,
          belongIdArray: arr,
          configKey: 'swipeReadyPicture',
          configValue: this.checkedUrl,
          creatorId: this.$store.state.user.userId,
          creatorName: this.$store.state.user.userName,
          extra: ''
        }).then(res => {
          if (res.data.status === 200) {
            this.$Message.success('设置成功！')
            this.setModalStatus = false
            this.getData()
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      } else {
        this.$Message.error('请选择一张待机动画图')
      }
    },
    // 点击设置与历史记录按钮
    setSlit (type, row) {
      this.historyStatus = true
      this.belongId = row.machineInstanceSoltId
      if (type === '1') {
        this.title = '机台设置'
        this.showType = '1'
        this.selectedImg = row.configValue
        this.getAnmanationList(row.configValue)
      } else {
        this.title = '历史记录'
        this.showType = '2'
        this.getHistoryList()
      }
    },
    // 获取待机动画列表
    awaitAnimationList (data, url) {
      lookAnimationList(data).then(res => {
        if (res.data.status === 200) {
          this.animationList = res.data.data
          if (data.shopId) {
            this.historyObj.total = res.data.totalCount
          } else {
            this.animationObj.total = res.data.totalCount
          }
          this.animationObj.total = res.data.totalCount
          if (this.animationList.length > 0) {
            this.animationList.forEach((ele, idx) => {
              if (ele.url === url) {
                this.checkedUrl = url
              }
            })
          } else {
            this.$Message.error('暂无数据！')
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 批量设置 弹窗二  动画列表
    gainAnimationList () {
      let param = {
        type: '',
        shopId: '',
        offset: this.animationObj.pageSize * (this.animationObj.pageIndex - 1),
        limit: this.animationObj.pageSize
      }
      this.awaitAnimationList(param, '')
    },
    // 获取待机动画列表 单个门店
    getAnmanationList () {
      let param = {
        type: '',
        shopId: this.$route.query.shopId,
        offset: this.historyObj.pageSize * (this.historyObj.pageIndex - 1),
        limit: this.historyObj.pageSize
      }
      this.awaitAnimationList(param, this.selectedImg)
    },
    // 关闭draw
    drawerSetClose () {
      this.historyStatus = false
    },
    // 选择需设置的动画
    selectMaterial (data) {
      this.animationList.forEach((ele, idx) => {
        if (ele.url === data.url) {
          // this.checkedId = data.deviceStandbyId
          this.checkedUrl = data.url
        }
      })
    },
    submit () {
      if (this.checkedUrl) {
        this.isDisabled = true
        setTimeout(() => {
          setSlitPort({
            merchantId: this.$store.state.user.merchantId,
            type: 1,
            belongIdArray: [this.belongId],
            configKey: 'swipeReadyPicture',
            configValue: this.checkedUrl,
            creatorId: this.$store.state.user.userId,
            creatorName: this.$store.state.user.userName,
            extra: ''
          }).then(res => {
            this.isDisabled = false
            if (res.data.status === 200) {
              this.historyStatus = false
              this.$Message.success('设置成功！')
              this.getData()
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }, 200)
      } else {
        this.$Message.error('请选择一张待机动画图')
      }
    },
    // 获取历史记录
    getHistoryList () {
      iterationHistoryList({
        merchantId: this.$store.state.user.merchantId,
        belongId: this.belongId,
        configKey: 'swipeReadyPicture',
        offset: this.historyObj.pageSize * (this.historyObj.pageIndex - 1),
        limit: this.historyObj.pageSize
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.tableHistoryData = result.data || []
          this.historyObj.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    },
    // 获取待机动画列表
    getData () {
      this.loading = true
      slitAnimationList({
        merchantId: this.$store.state.user.merchantId,
        shopName: this.$route.query.shopName,
        shopId: this.$route.query.shopId,
        machineName: this.machineName, // 机台名称
        machineCategoryId: this.machineType, // 分类ID
        state: this.operationStatus, // 更新状态 0：未执行，1：已执行
        offset: this.pageObj.pageSize * (this.pageObj.pageIndex - 1),
        limit: this.pageObj.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.tableData = result.data || []
          this.pageObj.total = result.totalCount || 0
        } else {
          this.$Message.error(`${result.error}`)
        }
      })
    }
  },
  created () {
    this.queryShopId = this.$route.query.shopId
    this.queryType = this.$route.query.type
    this.operationStatus = this.$route.query.type === '0' ? '0' : ''
    this.getMachineList()
  },
  mounted () {
    this.getData()
  }
}
</script>

<style lang='less'>
  #animation_slit{
    .search-box{
      .draw-btn{
        width: 80px;
      }
      .sign{
        display: block;
        width:8px;
        height: 20px;
        background: #2D8CF0;
      }
      .sign1{
        margin-left: 10px;
      }
    }
    .table-show {
      .animation-img{
        padding: 10px 0;
        img{
          width: 90px;
          height: 60px;
          display: block;
        }
      }
    }
    .twice-modal-set {
      .ivu-modal-body {
        padding: 0;
      }
      .animation-set{
        display: flex;
        flex-wrap: wrap;
        height: 392px;
        overflow: auto;
        dd {
          position: relative;
          width: 180px;
          margin: 18px 0 18px 36px;
          .check-icon{
            position: absolute;
            top: 2px;
            right: 2px;
          }
          img {
            display: block;
            width: 180px;
            height: 120px;
          }
          .desc {
            text-align: center;
            background: #F8F8F9;
            line-height: 40px;
            height: 40px;
          }
        }
      }
    }
  }
</style>
